import { createRouter, createWebHashHistory } from 'vue-router'
import store from '../store'
import Home from '@/components/Home.vue'
import API from '@/api'
import storage from '@/utils/storage'
import utils from './../utils/utils'

let routes = [
  {
    name: 'home',
    path: '/',
    meta: {
      title: '首页',
    },
    component: Home,
    redirect: '/welcome', // 重定向
    children: [
      {
        name: 'Welcome',
        path: '/welcome',
        meta: {
          title: '欢迎页面',
        },
        component: () => import('@/views/Welcome.vue'),
      },
    ],
  },
  {
    name: 'login',
    path: '/login',
    meta: {
      title: '登录',
    },
    component: () => import('@/views/Login.vue'),
  },
  {
    name: '404',
    path: '/404',
    meta: {
      title: '404错误',
    },
    component: () => import('@/views/404.vue'),
  },
  {
    path: '/:pathMatch(.*)',
    component: import('@/views/404.vue'),
  },
]

/**
 * @判断当前地址可否访问自写版本
 * @param {*} path 路径
 * @returns {Boolean}
 */
// function checkPermission(path) {
//   const hasRouter = router
//     .getRoutes()
//     .filter((item) => item.path == path).length
//   if (hasRouter) {
//     return true
//   } else {
//     return false
//   }
// }

export default async function() {
  const router = createRouter({
    history: createWebHashHistory(),
    scrollBehavior: () => ({ y: 0 }),
    routes,
  })
  let userInfo = storage.getItem('userInfo') || {}
  if (userInfo.token) {
    try {
      const { menuList } = await API.getPermissionList()
      for (const item of utils.generateRouter(menuList)) {
        item.component = () => import(`../views/${item.name}.vue`)
        router.addRoute('home', item)
      }
    } catch (error) {
      console.log(error)
    }
  }
  // 导航守卫
  router.beforeEach((to, from, next) => {
    // checkPermission(to.path) : 改用自带方法 router.hasRoute
    if (router.hasRoute(to.name)) {
      document.title = to.meta.title
      next()
    } else {
      next('/404')
    }
  })
  return router
}
